﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Nirvana
{
    public class WaitLoadObjectAsync : WaitLoadObject
    {
        private string assetpath;
        private string bundlename;
        private Type assettype;
        private AssetBundleManager abMgr;
        private AssetBundleRequest abRequest;

        public AssetBundleManager AssetBundleMgr
        {
            get { return abMgr; }
        }

        public string AssetPath
        {
            get { return assetpath; }
        }

        public  AssetBundleRequest AssetBundleRequest
        {
            get { return abRequest; }
        }

        public WaitLoadObjectAsync(AssetBundleManager mgr, string path,string bundlename,Type abtype)
        {
            abMgr = mgr;
            assetpath = path;
            this.bundlename = bundlename;
            assettype = abtype;
        }

        public WaitLoadObjectAsync(string format,params object[] args)
        {
            base.Error = string.Format(format, args);
        }


        public override bool keepWaiting
        {
            get
            {
                if(abRequest == null && base.Error != null)
                {
                    return false;
                }

                return !(abRequest != null && abRequest.isDone);
            }
        }

        public override bool Load()
        {
            AssetBundleItem item = this.abMgr.LoadAssetBundleItem(this.assetpath);
            if(item ==null) return true;
            if (!string.IsNullOrEmpty(item.error))
            {
                base.Error = item.error;
                return false;
            }
            if (abRequest == null) abRequest = item.assetbundle.LoadAssetAsync(bundlename, assettype);
            return false;
        }

        public override UnityEngine.Object GetObject()
        {
            if(abRequest != null && abRequest.isDone)
            {
                return this.abRequest.asset;
            }
            return null;
        }
    }
}

